package com.quanyan.place.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.assets.response.RespCoupon;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ServletUtils;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.ReqOrderOperate;
import com.quanyan.place.entity.apireq.ReqPlaceOrderInfo;
import com.quanyan.place.entity.apireq.ReqPlaceSalePlan;
import com.quanyan.place.entity.apireq.ReqPlaceTicketInfo;
import com.quanyan.place.entity.apireq.ReqTicketPayInfo;
import com.quanyan.place.entity.apireq.RespPlaceScale;
import com.quanyan.place.entity.apiresp.AvailableDate;
import com.quanyan.place.entity.apiresp.RespBizPlaceBaseInfo;
import com.quanyan.place.entity.apiresp.RespBizPlaceSalePlanOrderInfo;
import com.quanyan.place.entity.apiresp.RespCategoryAndScale;
import com.quanyan.place.entity.apiresp.RespCity;
import com.quanyan.place.entity.apiresp.RespImage;
import com.quanyan.place.entity.apiresp.RespPlaceUnitInfo;
import com.quanyan.place.entity.apiresp.RespPlaceUnitInfoVo;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlan;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanByDay;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanDetail;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanVo;
import com.quanyan.place.entity.apiresp.RespPlaceUserInfo;
import com.quanyan.place.entity.apiresp.RespVideo;
import com.quanyan.place.entity.base.apiresp.RespDistrict;
import com.quanyan.place.entity.dto.OrderHistoryDTO;
import com.quanyan.place.entity.dto.OrderItemCostDTO;
import com.quanyan.place.entity.dto.PayItemCostDTO;
import com.quanyan.place.entity.vo.PlaceMemberCardVo;
import com.quanyan.place.entity.vo.PlaceUnitSaleGroupVo;
import com.quanyan.place.mapper.PlaceUnitSalePlanMapper;
import com.quanyan.place.mapper.TbBizPlaceAttachMapper;
import com.quanyan.place.mapper.TbBizPlaceCategoryMapper;
import com.quanyan.place.mapper.TbBizPlaceMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderDiscountItemMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderHistoryMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderItemMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderManagerMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderMapper;
import com.quanyan.place.mapper.TbBizPlacePayItemMapper;
import com.quanyan.place.mapper.TbBizPlaceRuleMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMapper;
import com.quanyan.place.mapper.TbCityMapper;
import com.quanyan.place.mapper.TbDistrictMapper;
import com.quanyan.place.mapper.TbPlaceImageMapper;
import com.quanyan.place.mapper.TbPlaceTicketSalePlanMapper;
import com.quanyan.place.service.ApiPlaceOrderService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceMemberService;
import com.quanyan.place.service.PlaceUnitCombineService;
import com.quanyan.place.utils.PlaceOrderUtil;
import com.quanyan.place.utils.PlaceUtil;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_BASE;

/**
 * Created by zhaohui on 2016/11/23.
 */
@Service("apiPlaceOrderServiceImpl")
public class ApiPlaceOrderServiceImpl implements ApiPlaceOrderService {
    private static final Logger logger = LoggerFactory.getLogger(ApiPlaceOrderServiceImpl.class);
    
    public static final Map<String,List<PayItemCostDTO>> payItemMap = new ConcurrentHashMap<>();
    
    @Autowired
    TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;

    @Autowired
    TbPlaceImageMapper tbPlaceImageMapper;


    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;

    @Autowired
    IBaseService baseService;

    @Autowired
    TbCityMapper tbCityMapper;

    @Autowired
    TbDistrictMapper tbDistrictMapper;

    @Autowired
    TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

    @Autowired
    PlaceMemberService placeMemberService;


    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;

    @Autowired
    BaseServiceImpl baseServiceimpl;

    @Autowired
    TbBizPlaceUnitMapper placeUnitMapper;
    @Autowired
    PlaceUnitSalePlanMapper placeUnitSalePlanMapper;
    @Autowired
    PlaceUnitCombineService placeUnitCombineService;
    @Autowired
    PlaceRedisTemplate placeRedisTemplate;

    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;
    @Autowired
    TbBizPlaceOrderDiscountItemMapper discountItemMapper;

    @Autowired
    TbBizPlaceOrderHistoryMapper orderHistoryMapper;
    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;
    
    @Autowired
    private TbBizPlaceOrderDiscountItemMapper tbBizPlaceOrderDiscountItemMapper;

    /**
     * 获取销售计划
     * @param reqPlaceSalePlan
     * @return
     */
    @Override
    public APIResponse<RespPlaceUnitSalePlanDetail> getPlaceSalePlan(ReqPlaceSalePlan reqPlaceSalePlan) {

        RespPlaceUnitSalePlanDetail respPlaceUnitSalePlanDetail = placeSalePlanUtils(reqPlaceSalePlan);
        logger.info("1、-------->respPlaceUnitSalePlanDetail:{}",JSON.toJSONString(respPlaceUnitSalePlanDetail));
        if (respPlaceUnitSalePlanDetail == null) {
            return APIResponse.returnFail("不存在这天的销售计划！");
        }

        if (reqPlaceSalePlan.getCategoryId().intValue() == 2 || reqPlaceSalePlan.getCategoryId().intValue() == 4 ){
            //是否第一次请求，如果是第一次请求则选择销售计划未售出的那一天，isUseFirst如果是1 则表示第一次请求
            if (null != reqPlaceSalePlan.getIsUseFirst() ) {
                if (reqPlaceSalePlan.getIsUseFirst().equals(1)) {
                    List<AvailableDate> availableDates =  respPlaceUnitSalePlanDetail.getAvailableDateList();
                    for (AvailableDate availableDate : availableDates) {
                        if (availableDate.getIsSaleOut().equals(1)) {
                            reqPlaceSalePlan.setStartDate(DateTimeUtils.strToDate(availableDate.getDate()).getTime());
                            reqPlaceSalePlan.setEndDate(DateTimeUtils.strToDate(availableDate.getDate()).getTime());
                            respPlaceUnitSalePlanDetail = placeSalePlanUtils(reqPlaceSalePlan);
                            break;
                        }
                    }

                }
            }
            return APIResponse.returnSuccess(respPlaceUnitSalePlanDetail);
        }


        //组合销售
        if (null == reqPlaceSalePlan.getFieldScale() &&
                (reqPlaceSalePlan.getCategoryId().intValue() == 3 ||reqPlaceSalePlan.getCategoryId().intValue() == 1)){
            List<RespCategoryAndScale> categoryAndScales = respPlaceUnitSalePlanDetail.getCategoryAndScales();
            logger.info("ReqPlaceSalePlan::"+ JSON.toJSONString(reqPlaceSalePlan));
            if (CollectionUtils.isNotEmpty(categoryAndScales)){
                for (RespCategoryAndScale respCategory : respPlaceUnitSalePlanDetail.getCategoryAndScales()) {
                    Integer categoryId = respCategory.getId();
                    if (categoryId.intValue() == reqPlaceSalePlan.getCategoryId().
                            intValue()){
                        if (!org.springframework.util.CollectionUtils.isEmpty(respCategory.getRespPlaceScales())){
                            RespPlaceScale scale = respCategory.getRespPlaceScales().get(0);
                            reqPlaceSalePlan.setFieldScale(scale.getScaleId());
                        }
                    }
                }
            }
        }
        List<AvailableDate> availableDates =  getAvailableDateList(reqPlaceSalePlan);
        for (AvailableDate availableDate : availableDates) {
            if (availableDate.getIsSaleOut().equals(1)) {
                respPlaceUnitSalePlanDetail.setIsUseDate(DateTimeUtils.strToDate(availableDate.getDate()).getTime());
                //是否第一次请求，如果是第一次请求则选择销售计划未售出的那一天，isUseFirst如果是1 则表示第一次请求
                if (null != reqPlaceSalePlan.getIsUseFirst() ) {
                    if (reqPlaceSalePlan.getIsUseFirst().equals(1)) {
                        reqPlaceSalePlan.setStartDate(DateTimeUtils.strToDate(availableDate.getDate()).getTime());
                        reqPlaceSalePlan.setEndDate(DateTimeUtils.strToDate(availableDate.getDate()).getTime());
                        respPlaceUnitSalePlanDetail = placeSalePlanUtils(reqPlaceSalePlan);
                    }
                }
                break;
            }
        }
        respPlaceUnitSalePlanDetail.setAvailableDateList(availableDates);
        APIResponse response = placeUnitCombineService.combinePlaceUnit(reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId(),
                reqPlaceSalePlan.getFieldScale(),reqPlaceSalePlan.getStartDate(), reqPlaceSalePlan.getEndDate(),
                respPlaceUnitSalePlanDetail);
        return response;
    }


    public RespPlaceUnitSalePlanDetail placeSalePlanUtils(ReqPlaceSalePlan reqPlaceSalePlan) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer) httpServletRequest.getAttribute("uid");
        if (userId != null && userId > 0) {
            reqPlaceSalePlan.setUid(userId);
        } else {
            reqPlaceSalePlan.setUid(0);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("get sale plan list");
        RespPlaceUnitSalePlanDetail placeUnitSalePlanDetail = new RespPlaceUnitSalePlanDetail();
        placeUnitSalePlanDetail.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        placeUnitSalePlanDetail.setSystemCode(Constants.PLACE_SYSTEM_CODE);

        List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoList = new ArrayList<>();

        Date currDate = new Date(System.currentTimeMillis() - 60 * 60 * 1000);//当前时间前一小时
        Map<String, RespPlaceUnitSalePlanByDay> respPlaceUnitSalePlanByDayMap = new HashMap<>();
        Map<String, RespPlaceUnitInfoVo> respPlaceUnitInfoVoMap = new HashMap<>();
        Set<Integer> expiredBundleNoSet = new TreeSet<>();
        Set<Integer> orderBundleNoSet = new TreeSet<>();

       /* String earlyStartTime = null;  //最早的营业时间
        String lateEndTime = null;   //最晚的营业时间*/
        /**获取销售计划**/
        List<TbBizPlaceUnitSalePlan>  lists = getTbBizPlaceUnitSalePlanList(reqPlaceSalePlan);
        if (CollectionUtils.isNotEmpty(lists)) {
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : lists) {
                String date = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());

                if (!respPlaceUnitSalePlanByDayMap.containsKey(date)) {//根据date区分RespPlaceUnitSalePlanByDay
                    RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay = new RespPlaceUnitSalePlanByDay();
                    respPlaceUnitSalePlanByDay.setDate(date);
                    respPlaceUnitSalePlanByDay.setWeek(DateUtils.dayForWeek(date));
                    respPlaceUnitSalePlanByDayMap.put(date, respPlaceUnitSalePlanByDay);
                    placeUnitInfoVoList.add(respPlaceUnitSalePlanByDay);
                }

                RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay = respPlaceUnitSalePlanByDayMap.get(date);

                if (CollectionUtils.isEmpty(respPlaceUnitSalePlanByDay.getPlaceUnitList())) {
                    List<RespPlaceUnitInfoVo> respPlaceUnitInfoVoList = new ArrayList<>();
                    respPlaceUnitSalePlanByDay.setPlaceUnitList(respPlaceUnitInfoVoList);
                }

                List<RespPlaceUnitInfoVo> respPlaceUnitInfoVoList = respPlaceUnitSalePlanByDay.getPlaceUnitList();

                if (!respPlaceUnitInfoVoMap.containsKey(date + tbBizPlaceUnitSalePlan.getPlaceUnitId())) {
                    RespPlaceUnitInfoVo respPlaceUnitInfoVo = new RespPlaceUnitInfoVo();
                    RespPlaceUnitInfo respPlaceUnitInfo = new RespPlaceUnitInfo();
                    respPlaceUnitInfo.setId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                    respPlaceUnitInfo.setName(tbBizPlaceUnitSalePlan.getPlaceUnitName());//TODO 从数据库获取场地详情
                    respPlaceUnitInfoVo.setRespPlaceUnitInfo(respPlaceUnitInfo);
                    respPlaceUnitInfoVoMap.put(date + tbBizPlaceUnitSalePlan.getPlaceUnitId(), respPlaceUnitInfoVo);

                    respPlaceUnitInfoVoList.add(respPlaceUnitInfoVo);
                }
                RespPlaceUnitInfoVo respPlaceUnitInfoVo = respPlaceUnitInfoVoMap
                        .get(date + tbBizPlaceUnitSalePlan.getPlaceUnitId());

                if (CollectionUtils.isEmpty(respPlaceUnitInfoVo.getPlaceUnitSalePlanList())) {
                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = new ArrayList<>();
                    respPlaceUnitInfoVo.setPlaceUnitSalePlanList(placeUnitSalePlanList);

                }

                List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = respPlaceUnitInfoVo.getPlaceUnitSalePlanList();


                RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVo = new RespPlaceUnitSalePlanVo();
                RespPlaceUnitSalePlan respPlaceUnitSalePlan = new RespPlaceUnitSalePlan();
                if (PlaceConstants.PLACE_ORDER_STATUS.equals(tbBizPlaceUnitSalePlan.getStatus())
                        && PlaceConstants.YES.equals(reqPlaceSalePlan.getIsNeedUserInfo())) {
                    //查询新的用户系统
                    APIResponse<RespUserInfoBase> result = userServiceFacade
                            .queryUserInfo(tbBizPlaceUnitSalePlan.getOrderUid());
                    RespPlaceUserInfo userInfo = new RespPlaceUserInfo();
                    if (result.isRet()) {
                        try {
                            BeanUtils.copyProperties(result.getData(), userInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    RespBizPlaceSalePlanOrderInfo orderInfo = new RespBizPlaceSalePlanOrderInfo();
                    //获取订单时间
                    TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
                    tbBizPlaceOrderItemExample.createCriteria().andUnitSalePlanIdEqualTo(tbBizPlaceUnitSalePlan.getId());
                    List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = this
                            .tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
                    if (CollectionUtils.isNotEmpty(tbBizPlaceOrderItems)) {
                        orderInfo.setOrderTime(tbBizPlaceOrderItems.get(0).getCreateTime().getTime());
                        orderInfo.setOrderNo(tbBizPlaceOrderItems.get(0).getPlaceOrderId());
                    }
                    orderInfo.setUserInfo(userInfo);
                    respPlaceUnitSalePlanVo.setOrderInfo(orderInfo);
                }
                /**营业时间造成商家端销售计划与c端不同步**/
               /* String startTime = DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime());
                String endTime = DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime());
                if (null == earlyStartTime) {
                    earlyStartTime = startTime;
                } else {
                    if (startTime.compareTo(earlyStartTime) <= 0) {
                        earlyStartTime = startTime;
                    }
                }

                if (null == lateEndTime) {
                    lateEndTime = endTime;
                } else {
                    if (endTime.compareTo(lateEndTime) >= 0) {
                        lateEndTime = endTime;
                    }
                }*/

                //respPlaceUnitSalePlan.setStartTime(startTime);
                //respPlaceUnitSalePlan.setEndTime(endTime);
                respPlaceUnitSalePlan.setStartTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()));
                respPlaceUnitSalePlan.setEndTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));

                respPlaceUnitSalePlan.setPlaceId(tbBizPlaceUnitSalePlan.getPlaceId());
                respPlaceUnitSalePlan.setPlaceUnitId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                respPlaceUnitSalePlan.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
                respPlaceUnitSalePlan.setPrice(tbBizPlaceUnitSalePlan.getPrice());
                String salePlanDateString = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());

                //Date salePlanDate = DateUtils.dateStrToDate(salePlanDateString + " " + startTime + ":00");
                Date salePlanDate = DateUtils.dateStrToDate(salePlanDateString + " " + respPlaceUnitSalePlan.getStartTime() + ":00");
                if (tbBizPlaceUnitSalePlan.getBundleNo() == null) {
                    tbBizPlaceUnitSalePlan.setBundleNo(0);
                }
                //如果销售计划开始时间大于当前系统时间，设置为原始状态，否则设置为已售状态
                if (salePlanDate != null && salePlanDate.before(currDate)) {
                    respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);//预定状态
                    if (!tbBizPlaceUnitSalePlan.getBundleNo().equals(0)) {
                        expiredBundleNoSet.add(tbBizPlaceUnitSalePlan.getBundleNo());
                    }

                } else {
                    respPlaceUnitSalePlan.setStatus(tbBizPlaceUnitSalePlan.getStatus());
                }

                //如果捆绑组其中一个时段已经售出，该捆绑组全部都不能卖（商家端可以卖），存入orderBundleNoSet集合中，后续会处理
                if (!PlaceConstants.PLACE_PREORDER_STATUS.equals(tbBizPlaceUnitSalePlan.getStatus())) {
                    if (!tbBizPlaceUnitSalePlan.getBundleNo().equals(0)) {
                        orderBundleNoSet.add(tbBizPlaceUnitSalePlan.getBundleNo());
                    }
                }
                //同一组的销售计划开始时间过期，则这一组都设置为过期数据
                if (expiredBundleNoSet.contains(tbBizPlaceUnitSalePlan.getBundleNo())) {
                    respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);//预定状态
                }
                respPlaceUnitSalePlan.setDate(DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate()));
                respPlaceUnitSalePlan.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
                respPlaceUnitSalePlan.setLowestPrice(tbBizPlaceUnitSalePlan.getLowestPrice());
                respPlaceUnitSalePlan.setBundleNo(tbBizPlaceUnitSalePlan.getBundleNo());
                respPlaceUnitSalePlanVo.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);
                placeUnitSalePlanList.add(respPlaceUnitSalePlanVo);
            }

        }
        //根据运动类型id进行排序
        placeUnitSalePlanDetail.setPlaceUnitInfoVoList(placeUnitInfoVoList);
        List<RespCategoryAndScale> respCategoriess = new ArrayList<>();
        List<RespCategoryAndScale> respCategories = placeBaseService.getCategoryAndScale(reqPlaceSalePlan.getPlaceId(), true);
        if (CollectionUtils.isNotEmpty(respCategories)) {
            for (RespCategoryAndScale respCategory : respCategories) {
                if (respCategory.getId().intValue() == reqPlaceSalePlan.getCategoryId().intValue()) {
                    respCategoriess.add(0, respCategory);
                } else {
                    respCategoriess.add(respCategory);
                }
            }
            placeUnitSalePlanDetail.setCategoryAndScales(respCategoriess);
        }


        /**设置场馆是否包含门票**/
        placeUnitSalePlanDetail.setIsIncludeTicket(placeExistTicket(reqPlaceSalePlan.getPlaceId()));
        //日期段
        List<AvailableDate> availableDates =  getAvailableDateList(reqPlaceSalePlan);
        placeUnitSalePlanDetail.setAvailableDateList(availableDates);
        for (AvailableDate availableDate : availableDates) {
            if (availableDate.getIsSaleOut().equals(1)){
                placeUnitSalePlanDetail.setIsUseDate(DateTimeUtils.strToDate(availableDate.getDate()).getTime());
                break;
            }
        }

        Map map = this.placeUnitSalePlanMapper.getPlaceUnitTime(reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId());
        placeUnitSalePlanDetail.setStartTime(MapUtils.getString(map, "startTime"));
        placeUnitSalePlanDetail.setEndTime(MapUtils.getString(map, "endTime"));
       // placeUnitSalePlanDetail.setStartTime("08:00");
        //placeUnitSalePlanDetail.setEndTime("22:00");
        placeUnitSalePlanDetail.setIsContainVip(PlaceConstants.NO);
        /**获取场馆附属信息**/
        TbBizPlaceAttach tbBizPlaceAttach = getPlaceAttach(reqPlaceSalePlan.getPlaceId());
        if (null != tbBizPlaceAttach) {
            /**场馆营业时间**/
           // placeUnitSalePlanDetail.setStartTime(tbBizPlaceAttach.getBusinessHourStart());
           // placeUnitSalePlanDetail.setEndTime(tbBizPlaceAttach.getBusinessHourEnd());
            /**2017-4-24 注释 半点销售**/
            /**
             *  placeUnitSalePlanDetail.setOffsetTime(1);
             */


            //先判断全局开关是否支持会员，如果支持，在判断实际该场馆是否支持，如果全局不支持，则该场馆也不支持会员功能
           /* TbCommonParameter parameter = baseServiceimpl.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
            Byte isContainVip = 0;
            if (parameter != null && parameter.getParameterValue() != null) {
                isContainVip = Byte.valueOf(parameter.getParameterValue());
            }*/
            if (placeMemberService.isPlaceContainMemberCard(reqPlaceSalePlan.getPlaceId())
                    && tbBizPlaceAttach.getIsVip() == 1) {
                // 场馆支持会员卡
                placeUnitSalePlanDetail.setIsContainVip(tbBizPlaceAttach.getIsVip());
            } else {
                placeUnitSalePlanDetail.setIsContainVip(PlaceConstants.NO);
            }
        }

        /*String startTime = placeUnitSalePlanDetail.getStartTime();
        if (earlyStartTime != null && startTime.compareTo(earlyStartTime) >= 0) {
            startTime = earlyStartTime;
            placeUnitSalePlanDetail.setStartTime(startTime);
        }

        String endTime = placeUnitSalePlanDetail.getEndTime();
        if (lateEndTime != null && endTime.compareTo(lateEndTime) <= 0) {
            endTime = lateEndTime;
            placeUnitSalePlanDetail.setEndTime(endTime);
        }*/

        /***
         * 2017-4-24 修改注释 半点销售
         * //根据请求参数判断是否需要补全销售计划列表
         List<String> list = PlaceOrderUtil.getIntervalTimeList(placeUnitSalePlanDetail.getStartTime(),
         placeUnitSalePlanDetail.getEndTime(), placeUnitSalePlanDetail.getOffsetTime() * 60);
         placeUnitSalePlanDetail.setTimeList(list);
         */

        /**
         * 添加此段
         */
        TbBizPlaceCategory placeCategory = placeBaseService.getPlaceCategory(reqPlaceSalePlan.getPlaceId(),
                Integer.valueOf(reqPlaceSalePlan.getCategoryId()));
        int intervalTime = 1 ;
        if (null != placeCategory){
            intervalTime = PlaceUtil.getTimeInterval(placeCategory.getMinSaleTimeUnit());
        }

        List<String> list = PlaceOrderUtil.getIntervalTimeList(placeUnitSalePlanDetail.getStartTime(),
                placeUnitSalePlanDetail.getEndTime(), intervalTime);
        logger.info("------------->List：{}",JSON.toJSONString(list));
        placeUnitSalePlanDetail.setTimeList(list);

        //判断是否为会员
        if (reqPlaceSalePlan.getUid() > 0 && placeMemberService.isPlaceMember(reqPlaceSalePlan.getUid(),
                reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId(), 0)) {
            placeUnitSalePlanDetail.setIsMember(1);
            placeUnitSalePlanDetail.setMemberTips("您是本场馆尊贵会员，享受会员价优惠订场！");
        } else {
            placeUnitSalePlanDetail.setIsMember(0);
            placeUnitSalePlanDetail.setMemberTips("会员可享受更多折扣哦！点击");
        }

        /**场馆规则**/
        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList = tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        if (CollectionUtils.isEmpty(tbBizPlaceRuleList)) {
            //placeUnitSalePlanDetail.setIsContainOtherDate(PlaceConstants.CONTAIN_OTHER_DATE);//默认不显示其他日期
            placeUnitSalePlanDetail.setIsContainOtherDate(PlaceConstants.YES);//默认显示其它日期
            placeUnitSalePlanDetail.setSyncSalePlanCycle(PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD);
            placeUnitSalePlanDetail.setTips("温馨提示：本场馆仅支持提前" + PlaceConstants.PLACE_UNSUBSCRIBE_TIME + "小时退订！");
            placeUnitSalePlanDetail.setOnceOrderMaxTime(PlaceConstants.PLACE_ONCE_ORDER_MAX_TIME);
            logger.info("下单信息验证规则从默认配置中获取，placeId={}", reqPlaceSalePlan.getPlaceId());
        } else {
            placeUnitSalePlanDetail.setIsContainOtherDate(tbBizPlaceRuleList.get(0).getIsContainOtherDate());
            placeUnitSalePlanDetail.setSyncSalePlanCycle(tbBizPlaceRuleList.get(0).getSyncSalePlanCycle());
            placeUnitSalePlanDetail.setOnceOrderMaxTime(tbBizPlaceRuleList.get(0).getOnceOrderMaxTime());//用户一次可预定最大的时段总数
            if (tbBizPlaceRuleList.get(0).getUnsubscribeTime() > 0) {
                placeUnitSalePlanDetail.setTips("温馨提示：本场馆仅支持提前" + tbBizPlaceRuleList.get(0).getUnsubscribeTime() + "小时退订！");
            } else {
                placeUnitSalePlanDetail.setTips("温馨提示：本场馆不支持退订！");
            }

        }

        /**从场馆规则获取同步销售计划周期**/
        Byte isNormalDateInterval = PlaceConstants.NO;
       /* if (placeUnitSalePlanDetail.getSyncSalePlanCycle() > 0) {
            long startInterval = 7 * 86400000L;
            long endInterval = (placeUnitSalePlanDetail.getSyncSalePlanCycle() * 7 - 1) * 86400000L;
            if (placeUnitSalePlanDetail.getSyncSalePlanCycle() == 1) {
                startInterval = 0;
                endInterval = 0;
                isNormalDateInterval = PlaceConstants.YES;
            }
            long starttime = System.currentTimeMillis() + startInterval;
            long endtime = System.currentTimeMillis() + endInterval;
            if (reqPlaceSalePlan.getStartDate() <= endtime && reqPlaceSalePlan.getEndDate() <= endtime) {
                placeUnitSalePlanDetail.setExtendStartDate(starttime);
                placeUnitSalePlanDetail.setExtendEndDate(endtime);
                isNormalDateInterval = PlaceConstants.YES;
            }
        }*/

          if (placeUnitSalePlanDetail.getSyncSalePlanCycle() > 0) {
            long startInterval = 7 * 86400000L;


            long endInterval = (placeUnitSalePlanDetail.getSyncSalePlanCycle() * 7 - 1) * 86400000L;
            if (placeUnitSalePlanDetail.getSyncSalePlanCycle() == 1) {
                //startInterval = 0;
                placeUnitSalePlanDetail.setIsContainOtherDate((byte)0);
                //endInterval += startInterval;
                isNormalDateInterval = PlaceConstants.YES;
            }
            long starttime = System.currentTimeMillis() + startInterval;
            long endtime = System.currentTimeMillis() + endInterval;
            if (reqPlaceSalePlan.getStartDate() <= endtime && reqPlaceSalePlan.getEndDate() <= endtime) {
                placeUnitSalePlanDetail.setExtendStartDate(starttime);
                placeUnitSalePlanDetail.setExtendEndDate(endtime);
                isNormalDateInterval = PlaceConstants.YES;
            }
        }


        /*Integer interval = placeUnitSalePlanDetail.getSyncSalePlanCycle();
        interval = null != interval ? interval : 1;
        long startDays = DateTime.now().getMillis();
        long endtDays = DateTime.now().plusDays(interval * 7).getMillis();
        if (reqPlaceSalePlan.getStartDate() <= DateTime.now().getMillis() && reqPlaceSalePlan.getEndDate() <= DateTime.now().getMillis()) {
            placeUnitSalePlanDetail.setExtendStartDate(startDays);
            placeUnitSalePlanDetail.setExtendEndDate(endtDays);
            isNormalDateInterval = PlaceConstants.YES;
        }else{
            isNormalDateInterval = PlaceConstants.YES;
            if (PlaceConstants.YES.equals(placeUnitSalePlanDetail.getIsContainOtherDate().intValue())){

                placeUnitSalePlanDetail.setExtendStartDate(startDays);
                placeUnitSalePlanDetail.setExtendEndDate(endtDays);
            }
        }
*/
        if (PlaceConstants.YES.equals(reqPlaceSalePlan.getIsAutoCompleteSalePlan())
                && PlaceConstants.YES.equals(isNormalDateInterval)
                && CollectionUtils.isNotEmpty(placeUnitSalePlanDetail.getPlaceUnitInfoVoList())) {

            List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoListTemp = placeUnitSalePlanDetail.getPlaceUnitInfoVoList();
            for (RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay : placeUnitInfoVoListTemp) {
                List<RespPlaceUnitInfoVo> placeUnitList = respPlaceUnitSalePlanByDay.getPlaceUnitList();
                for (RespPlaceUnitInfoVo respPlaceUnitInfoVo : placeUnitList) {

                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = respPlaceUnitInfoVo.getPlaceUnitSalePlanList();

                    /**营业时间补全**/
                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanListTemp =
                            PlaceOrderUtil.getAllRespPlaceUnitSalePlanVoList(list, placeUnitSalePlanList);
                    //遍历销售计划列表，判断捆绑id是否存在于orderBundleNoSet集合中，如果存在置为已售状态。
                    for (RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVo : placeUnitSalePlanListTemp) {
                        RespPlaceUnitSalePlan respPlaceUnitSalePlan = respPlaceUnitSalePlanVo.getRespPlaceUnitSalePlan();
                        if (orderBundleNoSet.contains(respPlaceUnitSalePlan.getBundleNo())) {
                            respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                        }
                    }
                    respPlaceUnitInfoVo.setPlaceUnitSalePlanList(placeUnitSalePlanListTemp);
                }
            }
        } else if (PlaceConstants.YES.equals(reqPlaceSalePlan.getIsAutoCompleteSalePlan())
                && PlaceConstants.YES.equals(isNormalDateInterval)
                && CollectionUtils.isEmpty(placeUnitSalePlanDetail.getPlaceUnitInfoVoList())) {
            List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoListTemp = new ArrayList<>();
            RespPlaceUnitSalePlanByDay placeUnitSalePlanByDay = new RespPlaceUnitSalePlanByDay();
            List<RespPlaceUnitInfoVo> placeUnitListTemp = new ArrayList<>();

            TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
            TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();
            tbBizPlaceUnitCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
            tbBizPlaceUnitCriteria.andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId().byteValue());
            tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            tbBizPlaceUnitExample.setOrderByClause("name");//按照场地名称排序，+0将MySQL字符串字段按数值排序

            List<TbBizPlaceUnit> tbBizPlaceUnits = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);

            for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnits) {
                RespPlaceUnitInfo respPlaceUnitInfoTemp = new RespPlaceUnitInfo();
                respPlaceUnitInfoTemp.setId(tbBizPlaceUnit.getId());
                respPlaceUnitInfoTemp.setName(tbBizPlaceUnit.getName());
                RespPlaceUnitInfoVo respPlaceUnitInfoVoTemp = new RespPlaceUnitInfoVo();
                respPlaceUnitInfoVoTemp.setRespPlaceUnitInfo(respPlaceUnitInfoTemp);//场地详情

                List<RespPlaceUnitSalePlanVo> respPlaceUnitSalePlanVoList = new ArrayList<>();
                for (int i = 0; i < list.size() - 1; i++) {
                    RespPlaceUnitSalePlan respPlaceUnitSalePlan = new RespPlaceUnitSalePlan();
                    respPlaceUnitSalePlan.setStartTime(list.get(i));
                    respPlaceUnitSalePlan.setEndTime(list.get(i + 1));
                    respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                    RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVoTemp = new RespPlaceUnitSalePlanVo();
                    respPlaceUnitSalePlanVoTemp.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);
                    respPlaceUnitSalePlanVoList.add(respPlaceUnitSalePlanVoTemp);
                }
                respPlaceUnitInfoVoTemp.setPlaceUnitSalePlanList(respPlaceUnitSalePlanVoList);

                placeUnitListTemp.add(respPlaceUnitInfoVoTemp);
            }
            placeUnitSalePlanByDay.setPlaceUnitList(placeUnitListTemp);
            placeUnitSalePlanByDay.setDate(getAvailableDateList(reqPlaceSalePlan).get(0).getDate());
            placeUnitSalePlanByDay.setWeek(getAvailableDateList(reqPlaceSalePlan).get(0).getWeek());
            placeUnitInfoVoListTemp.add(placeUnitSalePlanByDay);
            placeUnitSalePlanDetail.setPlaceUnitInfoVoList(placeUnitInfoVoListTemp);
        }

        TbBizPlace tbBizPlace = getPlaceInfo(reqPlaceSalePlan.getPlaceId());
        if (null != tbBizPlace){
            placeUnitSalePlanDetail.setIsShelves(tbBizPlace.getIsShelves());
        }
        stopWatch.stop();
        logger.info(stopWatch.prettyPrint());
        return placeUnitSalePlanDetail;
    }



    /**
     * 是否可售
     * @param reqPlaceSalePlan
     * @return
     */
    public boolean isGroupSalePlanOut(ReqPlaceSalePlan reqPlaceSalePlan){
        Map<String,Object> map = new HashMap<>();
        map.put("placeId",reqPlaceSalePlan.getPlaceId());
        map.put("categoryId",reqPlaceSalePlan.getCategoryId());
        map.put("date",DateUtils.transferDateToString(reqPlaceSalePlan.getTempEndTime()));
        map.put("scaleId",reqPlaceSalePlan.getFieldScale());
        if (null != reqPlaceSalePlan.getFieldScale()){
            map.put("scaleId",reqPlaceSalePlan.getFieldScale());
        }
        List<PlaceUnitSaleGroupVo> tbBizPlaceUnitSalePlanList = tbBizPlaceOrderManagerMapper.getSalePlanOut(map);
        for (PlaceUnitSaleGroupVo placeUnitSaleGroupVo : tbBizPlaceUnitSalePlanList) {
            //普通
            if (placeUnitSaleGroupVo.getUnitType().equals((byte)0) && placeUnitSaleGroupVo.getStatus().equals((byte)1)){
                return true;
            }else if (placeUnitSaleGroupVo.getUnitType().equals((byte)1) && placeUnitSaleGroupVo.getStatus().equals((byte)1)){
                String subSalePlans = placeUnitSaleGroupVo.getSubSaleplans();
                if (!StringUtils.isEmpty(subSalePlans)){
                    String [] sub = subSalePlans.split("[|]");
                    map.put("listGroup",Arrays.asList(sub));
                    map.remove("scaleId");
                    List<PlaceUnitSaleGroupVo> tbBizPlaceUnitSalePlanList2 = tbBizPlaceOrderManagerMapper.getSalePlanOut(map);
                    if (!org.springframework.util.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanList2)){
                        int i = 0;
                        for (PlaceUnitSaleGroupVo unitSaleGroupVo : tbBizPlaceUnitSalePlanList2) {
                            if (unitSaleGroupVo.getStatus().equals((byte)1)){
                                i++;
                                // return true;
                            }
                        }
                        if (tbBizPlaceUnitSalePlanList2.size() == i){
                            return true;
                        }
                    }
                }

            }
        }
        return false;
    }


    /**
     * 获取今日起7天以后的时间段
     * @param reqPlaceSalePlan
     * @return
     */
    private List<AvailableDate> getAvailableDateList (ReqPlaceSalePlan reqPlaceSalePlan) {
        List<AvailableDate> availableDateList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {//TODO 天数从数据库查
            AvailableDate availableDate = new AvailableDate();
            long auctionTime = 0;
            if (reqPlaceSalePlan.getIsAuction() != null && reqPlaceSalePlan.getIsAuction().equals(1)) {
                auctionTime = 5 * 86400000L;
            }
            long temp = i * 86400000L + auctionTime;
            long time = System.currentTimeMillis() + temp;

            String date = DateUtils.transferLongToDateString(time);
            availableDate.setDate(date);
            availableDate.setWeek(DateUtils.dayForWeek(date));

            reqPlaceSalePlan.setTempEndTime(DateUtils.transferLongToDate(time));
            boolean result = isGroupSalePlanOut(reqPlaceSalePlan);
            if (result) {
                availableDate.setIsSaleOut(1);
            } else {
                availableDate.setIsSaleOut(0);
            }
            availableDateList.add(availableDate);
        }
        return availableDateList;
    }

    /**
     * 获取销售计划
     * @return
     */
    private List<TbBizPlaceUnitSalePlan> getTbBizPlaceUnitSalePlanList(ReqPlaceSalePlan reqPlaceSalePlan){
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria =
                tbBizPlaceUnitSalePlanExample.createCriteria();

        if (null != reqPlaceSalePlan.getPlaceId()){
            tbBizPlaceUnitSalePlanCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        }

        if (null != reqPlaceSalePlan.getCategoryId()){
            tbBizPlaceUnitSalePlanCriteria.andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId());
        }

        if (null != reqPlaceSalePlan.getStartDate()){
            Date startDate = DateUtils.transferLongToDate(reqPlaceSalePlan.getStartDate());
            tbBizPlaceUnitSalePlanCriteria.andDateEqualTo(startDate);
        }

        if (null != reqPlaceSalePlan.getEndDate() && null != reqPlaceSalePlan.getStartDate()){
            Date endDate = DateUtils.transferLongToDate(reqPlaceSalePlan.getEndDate());
            Date startDate = DateUtils.transferLongToDate(reqPlaceSalePlan.getStartDate());
            tbBizPlaceUnitSalePlanCriteria.andDateBetween(startDate, endDate);
        }

        /**处理营业时间与销售计划不匹配**/
        Map map = this.placeUnitSalePlanMapper.getPlaceUnitTime(reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId());
        if (!StringUtils.isEmpty(MapUtils.getString(map, "startTime"))) {
            tbBizPlaceUnitSalePlanCriteria.andStartTimeGreaterThanOrEqualTo(DateTimeUtils.convertString2Date("HH:mm:ss", MapUtils.getString(map, "startTime")));
        }
        if (!StringUtils.isEmpty(MapUtils.getString(map, "endTime"))) {
            tbBizPlaceUnitSalePlanCriteria.andEndTimeLessThanOrEqualTo(DateTimeUtils.convertString2Date("HH:mm:ss", MapUtils.getString(map, "endTime")));
        }

        tbBizPlaceUnitSalePlanCriteria.andIsEffectiveEqualTo(Constants.YES);
        tbBizPlaceUnitSalePlanCriteria.andUnitTypeEqualTo(UNIT_TYPE_BASE);
        tbBizPlaceUnitSalePlanExample.setOrderByClause("place_unit_name,start_time");//按照场地名称排序，+0将MySQL字符串字段按数值排序

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper
                .selectByExample(tbBizPlaceUnitSalePlanExample);
        return tbBizPlaceUnitSalePlanList;
    }

    /**
     * 场馆信息
     * @param placeId
     * @return
     */
    private TbBizPlace getPlaceInfo(Integer placeId){
        String placeIdKey = PlaceConstants.CACHE_PLACE_INFO_PREFIX+String.valueOf(placeId);
        TbBizPlace tbBizPlace = (TbBizPlace)
                placeRedisTemplate.get(placeIdKey);
        if(null != tbBizPlace){
            logger.info("从缓存读取：TbBizPlace信息 {}",JSON.toJSONString(tbBizPlace));
            return tbBizPlace;
        }else{
            tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
            logger.info("从数据库读取：TbBizPlace信息 {}",JSON.toJSONString(tbBizPlace));
            placeRedisTemplate.set(placeIdKey,tbBizPlace,PlaceConstants.PLACE_INFO_CACHE_TIME);
            return tbBizPlace;
        }
    }

    /**
     * 获取场馆附属信息
     * @param placeId
     * @return
     */
    private TbBizPlaceAttach getPlaceAttach(Integer placeId){
        String placeIdKey = PlaceConstants.CACHE_PLACE_ATTACH_INFO_PREFIX+String.valueOf(placeId);
        TbBizPlaceAttach tbBizPlaceAttach = (TbBizPlaceAttach)placeRedisTemplate.get(placeIdKey);
        if (null != tbBizPlaceAttach){
            logger.info("从缓存读取：TbBizPlaceAttach {}",JSON.toJSONString(tbBizPlaceAttach));
            return tbBizPlaceAttach;
        }else{
            TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
            TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = example.createCriteria();
            tbBizPlaceAttachCriteria.andPlaceIdEqualTo(placeId);
            List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);
            if (!org.springframework.util.CollectionUtils.isEmpty(result)){
                tbBizPlaceAttach = result.get(0);
                logger.info("从数据库读取：TbBizPlaceAttach {}",JSON.toJSONString(tbBizPlaceAttach));
                placeRedisTemplate.set(placeIdKey,tbBizPlaceAttach,PlaceConstants.PLACE_INFO_CACHE_TIME);
                return tbBizPlaceAttach;
            }
        }
        return null;
    }


    /**
     * 获取场馆基本信息
     * @param placeId
     * @return
     */
    @Override
    public APIResponse<RespBizPlaceBaseInfo> getPlaceBaseInfo(Integer placeId) {
        String placeIdKey = PlaceConstants.CACHE_PLACE_BASE_INFO_PREFIX+String.valueOf(placeId);
        RespBizPlaceBaseInfo cachePlaceBaseInfo = (RespBizPlaceBaseInfo)
                placeRedisTemplate.get(placeIdKey);
        if (null != cachePlaceBaseInfo){
            logger.info("从缓存读取：RespBizPlaceBaseInfo {}",JSON.toJSONString(cachePlaceBaseInfo));
            APIResponse.returnSuccess(cachePlaceBaseInfo);
        }else{
            RespBizPlaceBaseInfo respBizPlaceBaseInfo = new RespBizPlaceBaseInfo();
            //获取场馆基本信息
            TbBizPlace tbBizPlace = getPlaceInfo(placeId);
            if (tbBizPlace == null) {
                return APIResponse.returnFail("没有场馆信息");
            }
            //获取场馆图片信息
            TbPlaceImageExample tbPlaceImageExample = new TbPlaceImageExample();
            TbPlaceImageExample.Criteria tbPlaceImageCriteria = tbPlaceImageExample.createCriteria();
            tbPlaceImageCriteria.andTopicIdEqualTo(placeId);
            List<TbPlaceImage> tbPlaceImageList = tbPlaceImageMapper.selectUrlByExample(tbPlaceImageExample);
            List<RespImage> respImageList = new ArrayList<>();
            List<RespVideo> respVideoList = new ArrayList<>();
            for (TbPlaceImage tbPlaceImage : tbPlaceImageList) {
                if (PlaceConstants.PLACE_CONTENT_TYPE_IMAGE.equals(tbPlaceImage.getContentType())) {
                    RespImage respImage = new RespImage();
                    BeanUtils.copyProperties(tbPlaceImage, respImage);
                    respImageList.add(respImage);
                } else if (PlaceConstants.PLACE_CONTENT_TYPE_VIDEO.equals(tbPlaceImage.getContentType())) {
                    RespVideo respVideo = new RespVideo();
                    BeanUtils.copyProperties(tbPlaceImage, respVideo);
                    respVideoList.add(respVideo);
                    respBizPlaceBaseInfo.setVideoUrl(tbPlaceImage.getUrl());
                }
            }

            //获取场馆城市信息
            TbCity tbCity = tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
            //获取场馆区域信息
            TbDistrict tbDistrict = tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());
            //签约isSign为null置为0
            if (tbBizPlace.getIsSign() != null) {
                respBizPlaceBaseInfo.setIsSign(tbBizPlace.getIsSign());
            } else {
                respBizPlaceBaseInfo.setIsSign(PlaceConstants.IS_SIGN_NO);
            }
            respBizPlaceBaseInfo.setVideoUrl(null);//TODO  先返回null，运营如今没有录入视频，以后再放开
            respBizPlaceBaseInfo.setImages(respImageList);
            respBizPlaceBaseInfo.setVideos(respVideoList);
            RespCity respCity = new RespCity();
            BeanUtils.copyProperties(tbCity, respCity);
            respBizPlaceBaseInfo.setCityObj(respCity);

            RespDistrict respDistrict = new RespDistrict();
            BeanUtils.copyProperties(tbDistrict, respDistrict);
            respBizPlaceBaseInfo.setDistrictObj(respDistrict);
            BeanUtils.copyProperties(tbBizPlace, respBizPlaceBaseInfo);
            placeRedisTemplate.set(placeIdKey,respBizPlaceBaseInfo,PlaceConstants.PLACE_INFO_CACHE_TIME);
            logger.info("从数据库读取：RespBizPlaceBaseInfo {}",JSON.toJSONString(respBizPlaceBaseInfo));
            return APIResponse.returnSuccess(respBizPlaceBaseInfo);

        }
        return null;

    }

    /**
     * 场馆是否有门票
     * @param placeId
     * @return
     */
    private Integer placeExistTicket(Integer placeId){
        TbPlaceTicketSalePlanExample tbPlaceTicketSalePlanExample = new TbPlaceTicketSalePlanExample();
        TbPlaceTicketSalePlanExample.Criteria tbPlaceTicketSalePlanCriteria = tbPlaceTicketSalePlanExample.createCriteria();
        tbPlaceTicketSalePlanCriteria.andPlaceIdEqualTo(placeId);
        tbPlaceTicketSalePlanCriteria.andStatusEqualTo(PlaceConstants.YES);
        tbPlaceTicketSalePlanExample.setPage(new Page(0, 1));
        List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlans = tbPlaceTicketSalePlanMapper.selectByExample(tbPlaceTicketSalePlanExample);
        if (CollectionUtils.isNotEmpty(tbPlaceTicketSalePlans) && tbPlaceTicketSalePlans.size()>0) {
               return  1;
        }
        return 0;
    }

    /**
     * 在场馆营业时间范围内，填充该时段缺少的销售计划
     * @param list 营业时间段
     * @param dbPlaceUnitSalePlanVoList 可用的销售计划
     * @return
     */
    public static List<RespPlaceUnitSalePlanVo> getAllRespPlaceUnitSalePlanVoList(List<String> list,
                                                                                  List<RespPlaceUnitSalePlanVo> dbPlaceUnitSalePlanVoList) {
        //根据场馆营业时间得到原始的场馆销售计划
        List<RespPlaceUnitSalePlanVo> respPlaceUnitSalePlanVoList = new ArrayList<>();
        for (int i = 0; i < list.size() - 1; i++) {
            RespPlaceUnitSalePlan respPlaceUnitSalePlan = new RespPlaceUnitSalePlan();
            respPlaceUnitSalePlan.setStartTime(list.get(i));
            respPlaceUnitSalePlan.setEndTime(list.get(i + 1));
            respPlaceUnitSalePlan.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
            respPlaceUnitSalePlan.setBundleNo(0);
            RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVo = new RespPlaceUnitSalePlanVo();
            respPlaceUnitSalePlanVo.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);
            respPlaceUnitSalePlanVoList.add(respPlaceUnitSalePlanVo);
        }

        Comparator<RespPlaceUnitSalePlanVo> comparator = new Comparator<RespPlaceUnitSalePlanVo>() {
            @Override
            public int compare(RespPlaceUnitSalePlanVo o1, RespPlaceUnitSalePlanVo o2) {
                return o1.getRespPlaceUnitSalePlan().getStartTime()
                        .compareTo(o2.getRespPlaceUnitSalePlan().getStartTime());
            }
        };
        //原始的场馆销售计划与实际销售计划作差集
        List<RespPlaceUnitSalePlanVo> subTractList =
                (List<RespPlaceUnitSalePlanVo>) org.apache.commons.collections
                        .CollectionUtils.subtract(respPlaceUnitSalePlanVoList, dbPlaceUnitSalePlanVoList);

        //把经过以上步骤处理得到的差集与实际销售计划作并集，得到补全后的销售计划
        List<RespPlaceUnitSalePlanVo> unionList =
                (List<RespPlaceUnitSalePlanVo>) org.apache.commons
                        .collections.CollectionUtils.union(subTractList, dbPlaceUnitSalePlanVoList);

        //将补全后的销售计划按起始时间排序
        Collections.sort(unionList, comparator);
        return unionList;
    }

    /**
     * 拆分订单明细
     * @param orderItemCostDTO
     * @return
     */
    @Override
    public APIResponse setOrderItemCostService(OrderItemCostDTO orderItemCostDTO) {
        Integer orderType = orderItemCostDTO.getOrderType();
        /**1 订场***/
        if (PlaceConstants.ORDER_TYPE_BOOK.equals(orderType)){
            try {
                List<TbBizPlaceUnitSalePlan> placeUnitSalePlans = orderItemCostDTO.getTbBizPlaceUnitSalePlanList();

                for (TbBizPlaceUnitSalePlan placeUnitSalePlan : placeUnitSalePlans) {
                    TbBizPlaceOrderItem orderItem = new TbBizPlaceOrderItem();
                    orderItem.setPlaceOrderId(orderItemCostDTO.getReqPlaceOrderInfo().getOrderNo());
                    orderItem.setCategoryId(placeUnitSalePlan.getCategoryId());
                    orderItem.setSaleId(placeUnitSalePlan.getSaleId());
                    orderItem.setGoodsId(placeUnitSalePlan.getPlaceUnitId());
                    orderItem.setGoodsName(placeUnitSalePlan.getPlaceUnitName());
                    orderItem.setSurplusGoodsCount(1);
                    orderItem.setTotalGoodsCount(1);
                    orderItem.setItemUuid(UUIDUtils.getUUID());
                    orderItem.setUnitSalePlanId(placeUnitSalePlan.getId());
                    orderItem.setStartTime(placeUnitSalePlan.getStartTime());
                    orderItem.setEndTime(placeUnitSalePlan.getEndTime());
                    orderItem.setVersion(placeUnitSalePlan.getVersion());
                    orderItem.setUseType((byte)3);
                    TbBizPlaceMemberCard memberCard = orderItemCostDTO.getTbBizPlaceMemberCard();
                    if (memberCard != null){
                        if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(memberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(memberCard.getCardType())){
                            Double temp = new Double(memberCard.getDiscount()) / 100;
                            BigDecimal discount = new BigDecimal(temp);
                            BigDecimal discountAmount = placeUnitSalePlan.getMemberPrice().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
                            orderItem.setSalePrice(discountAmount);//设置打折后会员价
                        }
                        else {
                            orderItem.setSalePrice(placeUnitSalePlan.getMemberPrice());//设置会员价
                        }
                    }else{
                        orderItem.setSalePrice(placeUnitSalePlan.getPrice());
                    }

                    orderItem.setOriginPrice(placeUnitSalePlan.getPrice());
                    orderItem.setMemberPrice(placeUnitSalePlan.getMemberPrice());
                    orderItem.setTicketCount(1);
                    
                    String uuId = UUIDUtils.getUUID();
                    orderItem.setItemUuid(uuId);
                    orderItem.setConsumeTime(placeUnitSalePlan.getDate());
                    orderItemCostDTO.getSaleOrderMap().put(placeUnitSalePlan.getSaleId(), uuId);
                    //placeRedisTemplate.set(placeUnitSalePlan.getSaleId(),uuId,60*10);
                    tbBizPlaceOrderItemMapper.insertSelective(orderItem);
                }
            }catch (Exception e){
                logger.error("插入订场订单明细error：{}",e.getMessage());
                e.printStackTrace();
            }

        }else if (PlaceConstants.ORDER_TYPE_TICKET.equals(orderType)){
            /**2 门票***/
            try {
                ReqPlaceTicketInfo reqPlaceTicketInfo = orderItemCostDTO.getReqPlaceTicketInfo();
                List<ReqTicketPayInfo> ticketPayInfos = reqPlaceTicketInfo.getTicketPayInfos();
                PlaceMemberCardVo memberCard = reqPlaceTicketInfo.getPlaceMemberCardVo();
                for (ReqTicketPayInfo ticketPayInfo : ticketPayInfos) {
                	
                    TbPlaceTicketSalePlan ticketSalePlan = tbPlaceTicketSalePlanMapper.selectByPrimaryKey(ticketPayInfo.getSalePlanId());
                    if (null == ticketSalePlan){
                        return APIResponse.returnFail("没有可售的门票信息");
                    }
                    ticketPayInfo.setTicketSalePlan(ticketSalePlan);
                    
                    TbBizPlaceOrderItem orderItem = new TbBizPlaceOrderItem();
                    String uuId = UUIDUtils.getUUID();
                    orderItem.setItemUuid(uuId);

                    orderItem.setPlaceOrderId(orderItemCostDTO.getReqPlaceTicketInfo().getOrderNo());
                    orderItem.setUnitSalePlanId(ticketPayInfo.getSalePlanId());
                    if (null != memberCard){
                        orderItem.setSalePrice(ticketSalePlan.getMemberPrice().multiply(new BigDecimal(ticketPayInfo.getTicketCount())));
                    }else{
                        orderItem.setSalePrice(ticketSalePlan.getPrice().multiply(new BigDecimal(ticketPayInfo.getTicketCount())));
                    }
                    orderItem.setTicketCount(ticketPayInfo.getTicketCount());//票数
                    orderItem.setSaleId(ticketSalePlan.getSaleNo());
                    orderItem.setConsumeTime(new Date(orderItemCostDTO.getReqPlaceTicketInfo().getChooseDate()));//消费时间
                    orderItem.setCategoryId(ticketSalePlan.getCategoryId());
                    orderItem.setUseType((byte)2);
                    orderItem.setGoodsId(ticketSalePlan.getId());
                    orderItem.setGoodsName(ticketSalePlan.getTicketName());
                    orderItem.setSurplusGoodsCount(1);
                    orderItem.setTotalGoodsCount(1);
                    orderItem.setStartTime(ticketSalePlan.getStartTime());
                    orderItem.setEndTime(ticketSalePlan.getEndTime());
                    /**订单原价 = 商品原价*数量  **/
                    orderItem.setOriginPrice(ticketSalePlan.getPrice());
                    orderItem.setMemberPrice(ticketSalePlan.getMemberPrice());
                    orderItem.setConsumeTime(DateUtils.transferLongToDate(reqPlaceTicketInfo.getChooseDate()));
                    logger.debug("========================插入订单详情数据:TbBizPlaceOrder:{}", JSON.toJSONString(orderItem));
                    orderItemCostDTO.getSaleOrderMap().put(ticketSalePlan.getSaleNo(), uuId);
                    //placeRedisTemplate.set(ticketSalePlan.getSaleNo(),uuId,60*10);
                    tbBizPlaceOrderItemMapper.insert(orderItem);
                }
            }catch (Exception e){
                logger.error("插入门票订单明细error：{}",e.getMessage());
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     *  一个场地，对应多种支付方式
     *  一张门票，同上
     * @param orderItemCostDTO
     * @return
     */
    private Map<String,LinkedList<PayItemCostDTO>> saleIdToPayItemList(OrderItemCostDTO orderItemCostDTO){
        /**
         * 用linkedList的目的是为了确定 鸟蛋放到第一位，优惠券放最后一位，这样拆订单时先拆鸟蛋，再拆实付金额，最后计算出优惠券金额
         * **/
        Map<String,LinkedList<PayItemCostDTO>> map = new HashMap<>();
        List<ReqPayInfo> payInfoLists = orderItemCostDTO.getPayInfoList();
        Integer orderType = orderItemCostDTO.getOrderType();
        /**1 订场***/
        if (PlaceConstants.ORDER_TYPE_BOOK.equals(orderType)) {
            List<TbBizPlaceUnitSalePlan> placeUnitSalePlans = orderItemCostDTO.getTbBizPlaceUnitSalePlanList();
            
            for (TbBizPlaceUnitSalePlan placeUnitSalePlan : placeUnitSalePlans) {
            	//获取订单明细ID
                String uuid = orderItemCostDTO.getSaleOrderMap().get(placeUnitSalePlan.getSaleId());
                LinkedList<PayItemCostDTO> payItemCostDTOs = new LinkedList<>();
                
                for (ReqPayInfo payInfo : payInfoLists) {
                    PayItemCostDTO payItemCostDTO = new PayItemCostDTO();
                    payItemCostDTO.setAmount(payInfo.getAmount());
                    payItemCostDTO.setOrderItemUuid(uuid);
                    payItemCostDTO.setPayType(payInfo.getPayId());
                   
                    if (PlaceConstants.PAY_WAY_FOR_AGES.equals(payItemCostDTO.getPayType())){//鸟蛋支付
                        payItemCostDTOs.addFirst(payItemCostDTO);
                        
                    }else if (PlaceConstants.PAY_WAY_FOR_COUPON.equals(payItemCostDTO.getPayType())){//优惠券支付
                        payItemCostDTO.setCouponCode(payInfo.getSubjectCode());
                        payItemCostDTOs.addLast(payItemCostDTO);
                        
                    }else{
                    	//如果是会员卡支付，获取会员卡号
                        if (PlaceConstants.PAY_WAY_FOR_CARD.equals(payItemCostDTO.getPayType())) {
                            //Map<String, String> code = getPayTypeCode(orderItemCostDTO.getPayInfoList());
                            payItemCostDTO.setCardCode(orderItemCostDTO.getTbBizPlaceMemberCard().getInnerCardNo());
                        }
                        payItemCostDTOs.add(payItemCostDTO);
                    }
                }
                map.put(placeUnitSalePlan.getSaleId(), payItemCostDTOs);
            }
        }else if (PlaceConstants.ORDER_TYPE_TICKET.equals(orderType)){
            /**门票**/
            List<ReqTicketPayInfo> ticketPayInfoList = orderItemCostDTO.getReqPlaceTicketInfo().getTicketPayInfos();
            for (ReqTicketPayInfo ticketPayInfo : ticketPayInfoList) {
            	TbPlaceTicketSalePlan ticketSalePlan = ticketPayInfo.getTicketSalePlan();
            	//获取订单明细ID
                String uuid =  orderItemCostDTO.getSaleOrderMap().get(ticketSalePlan.getSaleNo());
                LinkedList<PayItemCostDTO> payItemCostDTOs = new LinkedList<>();

                for (ReqPayInfo payInfo : payInfoLists) {
                    PayItemCostDTO payItemCostDTO = new PayItemCostDTO();
                    payItemCostDTO.setAmount(payInfo.getAmount());
                    payItemCostDTO.setOrderItemUuid(uuid);
                    payItemCostDTO.setPayType(payInfo.getPayId());

                    if (PlaceConstants.PAY_WAY_FOR_AGES.equals(payItemCostDTO.getPayType())){//鸟蛋支付
                        payItemCostDTOs.addFirst(payItemCostDTO);

                    }else if (PlaceConstants.PAY_WAY_FOR_COUPON.equals(payItemCostDTO.getPayType())){//优惠券支付
                        payItemCostDTO.setCouponCode(payInfo.getSubjectCode());
                        payItemCostDTOs.addLast(payItemCostDTO);

                    }else{
                        //如果是会员卡支付，获取会员卡号
                        if (PlaceConstants.PAY_WAY_FOR_CARD.equals(payItemCostDTO.getPayType())) {
                            //Map<String, String> code = getPayTypeCode(orderItemCostDTO.getPayInfoList());
                            payItemCostDTO.setCardCode(orderItemCostDTO.getPlaceMemberCardVo().getInnerCardNo());
                        }
                        payItemCostDTOs.add(payItemCostDTO);
                    }
                }
                map.put(ticketSalePlan.getSaleNo(), payItemCostDTOs);
            }
        }
            return map;
    }

    /**
     * 1、先计算每个场地的鸟蛋
     * 2、实付金额
     * 3、优惠券
     * @param orderItemCostDTO
     * @return
     */
    private Map<String,LinkedList<PayItemCostDTO>> splitPayOrderItem(OrderItemCostDTO orderItemCostDTO){
        Map<String,LinkedList<PayItemCostDTO>> saleIdToPayItemList = saleIdToPayItemList(orderItemCostDTO);
        BigDecimal totalPrices = getUnitAmountByType(orderItemCostDTO);
        Map<Integer,BigDecimal> payAmount = getPayTypeMap(orderItemCostDTO.getPayInfoList());
        TbBizPlaceMemberCard tbBizPlaceMemberCard =  orderItemCostDTO.getTbBizPlaceMemberCard();
        boolean isMemberUser = isMemberUser(orderItemCostDTO);
        int index = 0;
        BigDecimal eggLastAmount = new BigDecimal(0);
        BigDecimal outLastAmount = new BigDecimal(0);
        BigDecimal couponLastAmount = new BigDecimal(0);
        List<TbBizPlaceUnitSalePlan> placeUnitSalePlans = orderItemCostDTO.getTbBizPlaceUnitSalePlanList();
        for (TbBizPlaceUnitSalePlan placeUnitSalePlan : placeUnitSalePlans) {
            index ++;
            String saleId = placeUnitSalePlan.getSaleId();
            BigDecimal unitPrice = null;
            if (isMemberUser){
            	unitPrice = placeUnitSalePlan.getMemberPrice();
            	if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())
                		||PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())) {
            		unitPrice = unitPrice.multiply(new BigDecimal(orderItemCostDTO.getTbBizPlaceMemberCard().getDiscount() / 100));
    			}
            }else {
                unitPrice = placeUnitSalePlan.getPrice();
            }

            /**计算实付金额**/
            BigDecimal salePrice = new BigDecimal(0);
            Integer payTypeId = getMapPayId(orderItemCostDTO.getPayInfoList());
            if (payAmount.containsKey(payTypeId)){
                BigDecimal outPrice = payAmount.get(payTypeId);
                if (index == placeUnitSalePlans.size()){
                    salePrice = outPrice.subtract(outLastAmount);
                }else{
                    salePrice = getPayAmount(unitPrice, outPrice, totalPrices);
                    outLastAmount = outLastAmount.add(salePrice);
                }
            }

            /**包含鸟蛋支付**/
            BigDecimal eggAmount = new BigDecimal(0);
            if (payAmount.containsKey(PlaceConstants.PAY_WAY_FOR_AGES.intValue())){
                BigDecimal eggCount = payAmount.get(PlaceConstants.PAY_WAY_FOR_AGES.intValue());
                if (index == placeUnitSalePlans.size()){
                    BigDecimal temAmount = eggLastAmount.divide(new BigDecimal(0.1),0,BigDecimal.ROUND_HALF_UP);
                    eggAmount = eggCount.subtract(temAmount).multiply(new BigDecimal(0.1));
                }else{
                    eggAmount = getEggAmount(totalPrices,unitPrice,eggCount);
                    eggLastAmount = eggLastAmount.add(eggAmount);
                }
            }

            /**计算优惠券**/
            BigDecimal couponPrice = new BigDecimal(0);
            if (payAmount.containsKey(PlaceConstants.PAY_WAY_FOR_COUPON.intValue())){
                if (index == placeUnitSalePlans.size()){
                    BigDecimal couponAmount = payAmount.get(PlaceConstants.PAY_WAY_FOR_COUPON.intValue());
                    couponPrice = couponAmount.subtract(couponLastAmount);
                }else{
                    couponPrice = getCouponAmount(unitPrice, salePrice, eggAmount);
                    couponLastAmount = couponLastAmount.add(couponPrice);
                }
            }

            /***根据saleId获取每场场地的支付明细**/
            LinkedList<PayItemCostDTO> payItemCostDTOs = saleIdToPayItemList.get(saleId);
            for (PayItemCostDTO payItemCostDTO : payItemCostDTOs) {
                int payType = payItemCostDTO.getPayType().intValue();
                if (payType == PlaceConstants.PAY_WAY_FOR_AGES.intValue()){
                    payItemCostDTO.setAmount(eggAmount.multiply(new BigDecimal(10)));
                }
                if (PlaceOrderUtil.getPayType().contains(payType)) {
                    payItemCostDTO.setPayType(payType);
                    payItemCostDTO.setAmount(salePrice);
                }
                if (payType == PlaceConstants.PAY_WAY_FOR_COUPON.intValue()){
                    payItemCostDTO.setAmount(couponPrice);
                }
            }
            saleIdToPayItemList.put(saleId, payItemCostDTOs);
        }
        logger.info(JSON.toJSONString(saleIdToPayItemList));
        return saleIdToPayItemList;

    }

    private Map<String,LinkedList<PayItemCostDTO>> splitPayOrderItemForTicket(OrderItemCostDTO orderItemCostDTO) throws BizException{
        Map<String,LinkedList<PayItemCostDTO>> saleIdToPayItemList = saleIdToPayItemList(orderItemCostDTO);
        ReqPlaceTicketInfo reqPlaceTicketInfo = orderItemCostDTO.getReqPlaceTicketInfo();
        List<ReqTicketPayInfo> ticketPayInfos = reqPlaceTicketInfo.getTicketPayInfos();
        Map<Integer,BigDecimal> payAmount = getPayTypeMap(orderItemCostDTO.getPayInfoList());

        int index = 0;
        BigDecimal eggLastAmount = new BigDecimal(0);
        BigDecimal outLastAmount = new BigDecimal(0);
        BigDecimal couponLastAmount = new BigDecimal(0);
        if(CollectionUtils.isEmpty(ticketPayInfos)){
            throw new BizException("没有门票销售计划");
        }

        /**计算总的应付金额**/
        BigDecimal totalPrices = new BigDecimal(0);
        for (ReqTicketPayInfo ticketPayInfo : ticketPayInfos) {
            TbPlaceTicketSalePlan ticketSalePlan = ticketPayInfo.getTicketSalePlan();

            /**将数据库查询得到的价格放入对象，方便再次使用**/
            ticketPayInfo.setMemberPrice(ticketSalePlan.getMemberPrice());
            ticketPayInfo.setPrice(ticketSalePlan.getPrice());

            BigDecimal ticketPrice;
            if (orderItemCostDTO.getPlaceMemberCardVo() != null){
                ticketPrice = ticketSalePlan.getMemberPrice().multiply(new BigDecimal(ticketPayInfo.getTicketCount()));
            }else {
                ticketPrice = ticketSalePlan.getPrice().multiply(new BigDecimal(ticketPayInfo.getTicketCount()));
            }
            totalPrices = totalPrices.add(ticketPrice);
        }

        for(ReqTicketPayInfo ticketPayInfo : ticketPayInfos){
        	index ++;
            String saleNo = ticketPayInfo.getTicketSalePlan().getSaleNo();
            BigDecimal unitPrice;
            //门票是不能打折的
            if (orderItemCostDTO.getPlaceMemberCardVo() != null){
                unitPrice = ticketPayInfo.getMemberPrice().multiply(new BigDecimal(ticketPayInfo.getTicketCount()));
            }else {
                unitPrice = ticketPayInfo.getPrice().multiply(new BigDecimal(ticketPayInfo.getTicketCount()));
            }

            /**计算实付金额**/
            BigDecimal salePrice = new BigDecimal(0);
            Integer payTypeId = getMapPayId(orderItemCostDTO.getPayInfoList());
            if (payAmount.containsKey(payTypeId)){
                BigDecimal outPrice = payAmount.get(payTypeId);
                if (index == ticketPayInfos.size()){
                    salePrice = outPrice.subtract(outLastAmount);
                }else{
                    salePrice = getPayAmount(unitPrice, outPrice, totalPrices);
                    outLastAmount = outLastAmount.add(salePrice);
                }
            }

            /**包含鸟蛋支付**/
            BigDecimal eggAmount = new BigDecimal(0);
            if (payAmount.containsKey(PlaceConstants.PAY_WAY_FOR_AGES.intValue())){
                BigDecimal eggCount = payAmount.get(PlaceConstants.PAY_WAY_FOR_AGES.intValue());
                if (index == ticketPayInfos.size()){
                    BigDecimal temAmount = eggLastAmount.divide(new BigDecimal(0.1),0,BigDecimal.ROUND_HALF_UP);
                    eggAmount = eggCount.subtract(temAmount).multiply(new BigDecimal(0.1));
                }else{
                    eggAmount = getEggAmount(totalPrices,unitPrice,eggCount);
                    eggLastAmount = eggLastAmount.add(eggAmount);
                }
            }

            /**计算优惠券**/
            BigDecimal couponPrice = new BigDecimal(0);
            if (payAmount.containsKey(PlaceConstants.PAY_WAY_FOR_COUPON.intValue())){
                if (index == ticketPayInfos.size()){
                    BigDecimal couponAmount = payAmount.get(PlaceConstants.PAY_WAY_FOR_COUPON.intValue());
                    couponPrice = couponAmount.subtract(couponLastAmount);
                }else{
                    couponPrice = getCouponAmount(unitPrice, salePrice, eggAmount);
                    couponLastAmount = couponLastAmount.add(couponPrice);
                }
            }

            /***根据saleId获取每场场地的支付明细**/
            LinkedList<PayItemCostDTO> payItemCostDTOs = saleIdToPayItemList.get(saleNo);
            for (PayItemCostDTO payItemCostDTO : payItemCostDTOs) {
                int payType = payItemCostDTO.getPayType().intValue();
                if (payType == PlaceConstants.PAY_WAY_FOR_AGES.intValue()){
                    payItemCostDTO.setAmount(eggAmount.multiply(new BigDecimal(10)));
                }
                if (PlaceOrderUtil.getPayType().contains(payType)) {
                    payItemCostDTO.setAmount(salePrice);
                }
                if (payType == PlaceConstants.PAY_WAY_FOR_COUPON.intValue()){
                    payItemCostDTO.setAmount(couponPrice);
                }
            }
        }
        logger.info(JSON.toJSONString(saleIdToPayItemList));
        return saleIdToPayItemList;

    }

    /**
     * 判断该用户是否为会员
     * @param orderItemCostDTO
     * @return
     */
    public static boolean isMemberUser(OrderItemCostDTO orderItemCostDTO){
        String cardNo = orderItemCostDTO.getReqPlaceOrderInfo().getCardNo();
        if (null == cardNo || cardNo.equals("")){
            return false;
        }
        return true;
    }
    /**
     * 计算鸟蛋
     * @param totalsPrice 订单金额
     * @param salePrice 销售价
     * @param eggCount 鸟蛋数
     * @return
     */
    private BigDecimal getEggAmount(BigDecimal totalsPrice,BigDecimal salePrice,BigDecimal eggCount){
        return eggCount.multiply(salePrice).divide(totalsPrice,2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(0.1)).setScale(1,BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 计算实付金额
     * @param outAmount 应付金额
     * @param salePrice 销售价
     * @param totalsPrice 实付金额
     * @return
     */
    private BigDecimal getPayAmount(BigDecimal salePrice,BigDecimal outAmount,BigDecimal totalsPrice){
        return salePrice.multiply(outAmount).divide(totalsPrice,2,BigDecimal.ROUND_HALF_UP).setScale(2,BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 计算优惠券金额
     * @param salePrice  销售价
     * @param unitPayAmount 一个格子实付金额
     * @param eggAmount 鸟蛋金额
     * @return
     */
    private BigDecimal getCouponAmount(BigDecimal salePrice,BigDecimal unitPayAmount,BigDecimal eggAmount){
        return salePrice.subtract(unitPayAmount).subtract(eggAmount);

    }


    /**
     * 根据用户的身份
     * 获取场地的会员价和散客价
     * @param orderItemCostDTO
     * @return
     */
    private BigDecimal getUnitAmountByType(OrderItemCostDTO orderItemCostDTO){
        List<TbBizPlaceUnitSalePlan> placeUnitSalePlans = orderItemCostDTO.getTbBizPlaceUnitSalePlanList();
        BigDecimal originPrice = new BigDecimal(0);
        BigDecimal memberPrice = new BigDecimal(0);
        for (TbBizPlaceUnitSalePlan placeUnitSalePlan : placeUnitSalePlans) {
            /**原价**/
            originPrice = originPrice.add(placeUnitSalePlan.getPrice());
            /**会员价**/
            memberPrice = memberPrice.add(placeUnitSalePlan.getMemberPrice());
        }
        BigDecimal currentPrice = new BigDecimal(0);
        boolean result = isMemberUser(orderItemCostDTO);
        if (result){
            currentPrice = currentPrice.add(memberPrice);
            //折扣卡的话打个折
            if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(orderItemCostDTO.getTbBizPlaceMemberCard().getCardType())
            		||PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(orderItemCostDTO.getTbBizPlaceMemberCard().getCardType())) {
            	currentPrice = currentPrice.multiply(new BigDecimal(orderItemCostDTO.getTbBizPlaceMemberCard().getDiscount() / 100));
			}
        }else{
            currentPrice = currentPrice.add(originPrice);
        }
        return currentPrice;
    }

    /**
     * 拆分折扣优惠明细
     * 1.普通支付 可以鸟蛋、优惠卷一起使用
     * 2.会员卡支付 只能和优惠卷一起使用，不支持鸟蛋
     * @param orderItemCostDTO
     * @return
     *
     */
    @Override
    public APIResponse setOrderDiscountItemCostService(OrderItemCostDTO orderItemCostDTO) {
        Integer orderType = orderItemCostDTO.getOrderType();
        RespCoupon respCoupon = orderItemCostDTO.getRespCoupon();
        //1.订场
        if (PlaceConstants.ORDER_TYPE_BOOK.equals(orderType)) {
            try {
                //会员卡
                TbBizPlaceMemberCard tbBizPlaceMemberCard = orderItemCostDTO.getTbBizPlaceMemberCard();
                ReqPlaceOrderInfo reqPlaceOrderInfo = orderItemCostDTO.getReqPlaceOrderInfo();
                List<TbBizPlaceUnitSalePlan> placeUnitSalePlans = orderItemCostDTO.getTbBizPlaceUnitSalePlanList();
                
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : placeUnitSalePlans) {
					TbBizPlaceOrderDiscountItem orderDiscountItem = new TbBizPlaceOrderDiscountItem();
					orderDiscountItem.setPlaceOrderId(reqPlaceOrderInfo.getOrderNo());
					orderDiscountItem.setOrderItemUuid(orderItemCostDTO.getSaleOrderMap().get(tbBizPlaceUnitSalePlan.getSaleId()));
					orderDiscountItem.setStatus(PlaceConstants.ORDER_PAYED_STATUS.intValue());
					//会员
					if (tbBizPlaceMemberCard != null) {
						orderDiscountItem.setMemberCardNo(tbBizPlaceMemberCard.getInnerCardNo());
						orderDiscountItem.setDiscountMember(tbBizPlaceUnitSalePlan.getPrice().subtract(tbBizPlaceUnitSalePlan.getMemberPrice()));
						
						//折扣卡
					     if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) 
					    		 || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
					    	 
			                 BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount() / 100);
			                 BigDecimal discountAmount = tbBizPlaceUnitSalePlan.getMemberPrice().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
					    	 orderDiscountItem.setDiscountDiscountMember(tbBizPlaceUnitSalePlan.getMemberPrice().subtract(discountAmount));
					    }
					}
					 //获取拆分的支付明细
				    LinkedList<PayItemCostDTO> payItemCostDTOList =  orderItemCostDTO.getPayItemMap().get(tbBizPlaceUnitSalePlan.getSaleId());
				    for (PayItemCostDTO payItemCostDTO : payItemCostDTOList) {
			    		 BigDecimal amount = payItemCostDTO.getAmount();
				    	//鸟蛋
				    	if (PlaceConstants.PAY_WAY_FOR_AGES.equals(payItemCostDTO.getPayType())) {
				    		orderDiscountItem.setDiscountEgg(amount.divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP));
				    		orderDiscountItem.setEggCount(amount != null ? amount.intValue():0);
						}
				    	//优惠卷
                        if (PlaceConstants.PAY_WAY_FOR_COUPON.equals(payItemCostDTO.getPayType())) {
                        	if (respCoupon != null && respCoupon.getCouponType() == 2) {//折扣卷
                        		orderDiscountItem.setDiscountDiscountCoupon(amount);
                        		orderDiscountItem.setSubjectDiscount(respCoupon.getDiscount() != null? respCoupon.getDiscount().intValue() : 100);
							} else{
								orderDiscountItem.setDiscountCoupon(amount);
								orderDiscountItem.setSubjectAmount(respCoupon.getCouponAmount());
							}
                        	orderDiscountItem.setSubjectCode(payItemCostDTO.getCouponCode());
						}
					}
				    orderDiscountItem.setCreateTime(new Date());
				    orderDiscountItem.setUpdateTime(new Date());
				    logger.info("插入订单折扣优惠明细：{}", JSON.toJSONString(orderDiscountItem));
				    tbBizPlaceOrderDiscountItemMapper.insertSelective(orderDiscountItem);
				}

            }catch (Exception e){
                logger.error("插入订单折扣优惠明细error：{}",e.getMessage());
                e.printStackTrace();
                return APIResponse.returnFail("插入订单折扣优惠明细失败");
            }

         //2.门票
        }else if (PlaceConstants.ORDER_TYPE_TICKET.equals(orderType)){
            try {
            	ReqPlaceTicketInfo reqPlaceTicketInfo = orderItemCostDTO.getReqPlaceTicketInfo();
                List<ReqTicketPayInfo> ticketPayInfos = reqPlaceTicketInfo.getTicketPayInfos();
                PlaceMemberCardVo memberCard = reqPlaceTicketInfo.getPlaceMemberCardVo();
                
                for (ReqTicketPayInfo ticketPayInfo : ticketPayInfos) {
                    TbPlaceTicketSalePlan ticketSalePlan = ticketPayInfo.getTicketSalePlan();
                    if (null == ticketSalePlan) {
                        return APIResponse.returnFail("没有可售的门票信息");
                    }
            		TbBizPlaceOrderDiscountItem orderDiscountItem = new TbBizPlaceOrderDiscountItem();
					orderDiscountItem.setPlaceOrderId(reqPlaceTicketInfo.getOrderNo());
					orderDiscountItem.setOrderItemUuid(orderItemCostDTO.getSaleOrderMap().get(ticketSalePlan.getSaleNo()));
					orderDiscountItem.setStatus(PlaceConstants.ORDER_PAYED_STATUS.intValue());
                    //会员优惠，门票不能打折
					if (memberCard != null) {
						orderDiscountItem.setMemberCardNo(memberCard.getInnerCardNo());
						orderDiscountItem.setDiscountMember(ticketSalePlan.getPrice().subtract(ticketSalePlan.getMemberPrice())
								.multiply(new BigDecimal(ticketPayInfo.getTicketCount())));
						//如果是次卡，记录次卡优惠
						if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(memberCard.getCardType())) {
							orderDiscountItem.setDiscountNumberMember(ticketSalePlan.getMemberPrice().subtract(memberCard.getNumberPrice())
								.multiply(new BigDecimal(ticketPayInfo.getTicketCount())));
						}
					}
					//获取拆分的支付明细
				    LinkedList<PayItemCostDTO> payItemCostDTOList =  orderItemCostDTO.getPayItemMap().get(ticketSalePlan.getSaleNo());
				    for (PayItemCostDTO payItemCostDTO : payItemCostDTOList) {
			    		 BigDecimal amount = payItemCostDTO.getAmount();
				    	//鸟蛋
				    	if (PlaceConstants.PAY_WAY_FOR_AGES.equals(payItemCostDTO.getPayType())) {
				    		orderDiscountItem.setDiscountEgg(amount.divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP));
				    		orderDiscountItem.setEggCount(amount != null ? amount.intValue():0);
						}
				    	//优惠卷
                     if (PlaceConstants.PAY_WAY_FOR_COUPON.equals(payItemCostDTO.getPayType())) {
                    	 if (respCoupon != null && respCoupon.getCouponType() == 2) {//门票可以使用折扣卷，不能使用折扣卡
                     		   orderDiscountItem.setDiscountDiscountCoupon(amount);
                     		   orderDiscountItem.setSubjectDiscount(respCoupon.getDiscount() != null? respCoupon.getDiscount().intValue() : 10);
							} else {
								orderDiscountItem.setDiscountCoupon(amount);
								orderDiscountItem.setSubjectAmount(respCoupon.getCouponAmount());
							}
                     	     orderDiscountItem.setSubjectCode(payItemCostDTO.getCouponCode());
						}
					}
				    orderDiscountItem.setCreateTime(new Date());
				    orderDiscountItem.setUpdateTime(new Date());
				    logger.info("插入订单折扣优惠明细：{}", JSON.toJSONString(orderDiscountItem));
				    tbBizPlaceOrderDiscountItemMapper.insertSelective(orderDiscountItem);
                }

            }catch (Exception e){
                logger.error("插入门票订单折扣明细error：{}",e.getMessage());
                e.printStackTrace();
                return APIResponse.returnFail("插入门票订单折扣明细失败");
            }
        }
        return null;
    }

    /**
     * 拆分支付方式
     * @param orderItemCostDTO
     * @return
     */
    @Override
    public APIResponse setOrderPayItemCostService(OrderItemCostDTO orderItemCostDTO){
        Integer orderType = orderItemCostDTO.getOrderType();
        /**1 订场***/
        if (PlaceConstants.ORDER_TYPE_BOOK.equals(orderType)) {
            try {
                ReqPlaceOrderInfo reqPlaceOrderInfo = orderItemCostDTO.getReqPlaceOrderInfo();
                Map<String,LinkedList<PayItemCostDTO>> mapPayItem = splitPayOrderItem(orderItemCostDTO);
                orderItemCostDTO.setPayItemMap(mapPayItem);
                for(Map.Entry<String,LinkedList<PayItemCostDTO>> entry: mapPayItem.entrySet()){
                    LinkedList<PayItemCostDTO> linkedList = entry.getValue();
                    for (PayItemCostDTO payItemCostDTO : linkedList) {
                        TbBizPlacePayItem payItem = new TbBizPlacePayItem();
                        payItem.setPayType(payItemCostDTO.getPayType());
                        payItem.setAmount(payItemCostDTO.getAmount());
                        payItem.setAdminPayType(PlaceOrderUtil.getAdminPayType(payItemCostDTO.getPayType()));
                        if (payItemCostDTO.getPayType().intValue() == PlaceConstants.PAY_WAY_FOR_AGES.intValue()){
                            payItem.setAmount(payItemCostDTO.getAmount());
                        }
                        if (payItemCostDTO.getPayType().intValue() == PlaceConstants.PAY_WAY_FOR_COUPON.intValue()){
                            payItem.setSubjectCode(payItemCostDTO.getCouponCode());
                        }
                        if (payItemCostDTO.getPayType().intValue() == PlaceConstants.PAY_WAY_FOR_CARD.intValue()){
                            payItem.setSubjectCode(payItemCostDTO.getCardCode());
                            if (orderItemCostDTO.getTbBizPlaceMemberCard() != null &&
                                    Constants.BYTE_ONE == orderItemCostDTO.getTbBizPlaceMemberCard().getIsOldMember()){
                                // 老会员卡 按照与场馆老板结算费方式处理
                            	payItem.setPayType(Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
                            	payItem.setAdminPayType(Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
                            }
                        }
                        payItem.setOrderItemUuid(payItemCostDTO.getOrderItemUuid());
                        payItem.setPlaceOrderId(reqPlaceOrderInfo.getOrderNo());
                        payItem.setAmountType(PlaceConstants.DEBIT_TYPE);
                        payItem.setCreateTime(new Date());
                        payItem.setUpdateTime(new Date());
                        tbBizPlacePayItemMapper.insert(payItem);
                    }
                }
            }catch (Exception e){
                logger.error("插入订场订单支付error：{}",e.getMessage());
                e.printStackTrace();
            }
        }else if (PlaceConstants.ORDER_TYPE_TICKET.equals(orderType)){
            try {
                /**门票**/
                ReqPlaceTicketInfo reqPlaceTicketInfo = orderItemCostDTO.getReqPlaceTicketInfo();
                Map<String,LinkedList<PayItemCostDTO>> mapPayItem = splitPayOrderItemForTicket(orderItemCostDTO);
                orderItemCostDTO.setPayItemMap(mapPayItem);
                
                for(Map.Entry<String,LinkedList<PayItemCostDTO>> entry: mapPayItem.entrySet()){
                    LinkedList<PayItemCostDTO> linkedList = entry.getValue();
                    for (PayItemCostDTO payItemCostDTO : linkedList) {
                        TbBizPlacePayItem payItem = new TbBizPlacePayItem();
                        payItem.setPayType(payItemCostDTO.getPayType());
                        payItem.setAmount(payItemCostDTO.getAmount());
                        payItem.setAdminPayType(PlaceOrderUtil.getAdminPayType(payItemCostDTO.getPayType()));
                        if (payItemCostDTO.getPayType().intValue() == PlaceConstants.PAY_WAY_FOR_AGES.intValue()){
                            payItem.setAmount(payItemCostDTO.getAmount());
                        }
                        if (payItemCostDTO.getPayType().intValue() == PlaceConstants.PAY_WAY_FOR_COUPON.intValue()){
                            payItem.setSubjectCode(payItemCostDTO.getCouponCode());
                        }
                        if (payItemCostDTO.getPayType().intValue() == PlaceConstants.PAY_WAY_FOR_CARD.intValue()){
                            payItem.setSubjectCode(payItemCostDTO.getCardCode());
                            if (orderItemCostDTO.getPlaceMemberCardVo() != null &&
                                    Constants.BYTE_ONE == orderItemCostDTO.getPlaceMemberCardVo().getIsOldMember()){
                                // 老会员卡 按照与场馆老板结算费方式处理
                            	payItem.setPayType(Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
                            	payItem.setAdminPayType(Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
                            }
                        }
                        payItem.setOrderItemUuid(payItemCostDTO.getOrderItemUuid());
                        payItem.setPlaceOrderId(reqPlaceTicketInfo.getOrderNo());
                        payItem.setAmountType(PlaceConstants.DEBIT_TYPE);
                        payItem.setCreateTime(new Date());
                        payItem.setUpdateTime(new Date());
                        tbBizPlacePayItemMapper.insert(payItem);
                    }
                }
            }catch (Exception e){
                logger.error("插入门票订单支付error：{}",e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 支付方式转Map这样减少遍历次数，方便使用
     * @param payInfoLists
     * @return
     */
    private Map<Integer,BigDecimal> getPayTypeMap( List<ReqPayInfo> payInfoLists){
        Map<Integer,BigDecimal> map = new HashMap<>();
        for (ReqPayInfo payInfoList : payInfoLists) {
            map.put(payInfoList.getPayId(),payInfoList.getAmount());
        }
        return map;
    }


    /***
     * 支付方式
     * @param payInfoLists
     * @return
     */
    private static Integer getMapPayId(List<ReqPayInfo> payInfoLists){
        List<Integer> a = new ArrayList<>();
        a.add(PlaceConstants.PAY_WAY_ALIPAY);
        a.add(PlaceConstants.PAY_WAY_WEICHAT);
        a.add(PlaceConstants.PAY_WAY_WEICHATH5);
        a.add(PlaceConstants.PAY_WAY_FOR_CARD);
        a.add(PlaceConstants.PAY_WAY_FOR_WEIXIN_APPLET);
        a.add(PlaceConstants.PAY_WAY_FOR_WEB_ALIPAY);
        for (ReqPayInfo payInfoList : payInfoLists) {
            if (a.contains(payInfoList.getPayId())){
                return payInfoList.getPayId();
            }
        }
        return null;
    }


    /**
     *
     * 回调订单状态设置
     * @param orderItemCostDTO
     * @return
     */
    @Override
    public APIResponse callBackOrderStatus(OrderItemCostDTO orderItemCostDTO) {
        ReqOrderOperate orderOperate = orderItemCostDTO.getReqOrderOperate();
        String placeOrderId = orderOperate.getOrderNo();
        /**callBackType: 回调类型 1：支付成功回调，2、退款成功回调,3、取消订单 ***/
        Integer callBackType = orderOperate.getCallBackType();
        /**更新订单明细状态**/
        TbBizPlaceOrderItemExample orderItemExample = new TbBizPlaceOrderItemExample();
        TbBizPlaceOrderItemExample.Criteria  orderItemExampleCriteria = orderItemExample.createCriteria();
        orderItemExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrderItem> orderItemList = tbBizPlaceOrderItemMapper.selectByExample(orderItemExample);
        if (null != orderItemList && orderItemList.size()>0){
            TbBizPlaceOrderItem orderItem = new TbBizPlaceOrderItem();
            if (callBackType.equals(1)){
                /**已付款*/
                orderItem.setStatus(3);
            }else if (callBackType.equals(2)){
                /**退款完成**/
                orderItem.setStatus(5);
            }else if (callBackType.equals(3)){
                /**订单关闭**/
                orderItem.setStatus(2);
            }else if (callBackType.equals(4)){
                /**订单退款中**/
                orderItem.setStatus(4);
            }
            tbBizPlaceOrderItemMapper.updateByExampleSelective(orderItem,orderItemExample);
        }


        /**更新折扣明细状态**/
        TbBizPlaceOrderDiscountItemExample orderDiscountItemExample = new TbBizPlaceOrderDiscountItemExample();
        TbBizPlaceOrderDiscountItemExample.Criteria orderDiscountItemExampleCriteria = orderDiscountItemExample.createCriteria();
        orderDiscountItemExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrderDiscountItem> orderDiscountItems= discountItemMapper.selectByExample(orderDiscountItemExample);
        if (null != orderDiscountItems && orderDiscountItems.size()>0){
            TbBizPlaceOrderDiscountItem orderDiscountItem = new TbBizPlaceOrderDiscountItem();
            if (callBackType.equals(1)){
                /**已付款*/
                orderDiscountItem.setStatus(3);
            }else if (callBackType.equals(2)){
                /**退款完成**/
                orderDiscountItem.setStatus(5);
            }else if (callBackType.equals(3)){
                /**订单关闭**/
                orderDiscountItem.setStatus(2);
            }else if (callBackType.equals(4)){
                /**订单退款中**/
                orderDiscountItem.setStatus(4);
            }
            discountItemMapper.updateByExampleSelective(orderDiscountItem,orderDiscountItemExample);
        }

        /**付款明细 amount_type 2：支出**/
        if (callBackType.equals(2)){
            TbBizPlacePayItem payItem = new TbBizPlacePayItem();
            payItem.setAmountType((byte)2);
            TbBizPlacePayItemExample payItemExample = new TbBizPlacePayItemExample();
            TbBizPlacePayItemExample.Criteria payItemExampleCriteria = payItemExample.createCriteria();
            payItemExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
            tbBizPlacePayItemMapper.updateByExampleSelective(payItem,payItemExample);
        }
        return null;
    }

    private List<TbBizPlaceOrderItem> getPlaceOrderItem (String orderNo){
        TbBizPlaceOrderItemExample orderItem = new TbBizPlaceOrderItemExample();
        orderItem.createCriteria().andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlaceOrderItem> placeOrderItem = this.tbBizPlaceOrderItemMapper.selectByExample(orderItem);
        return placeOrderItem;
    }

    private TbBizPlaceOrder getPlaceOrder(String orderNo){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if (null != tbBizPlaceOrders && tbBizPlaceOrders.size()>0){
            return tbBizPlaceOrders.get(0);
        }
        return null;

    }


    @Override
    public APIResponse insertOrderHistory(OrderHistoryDTO orderHistoryDTO) {
        logger.info("插入订单历史记录：{}",JSON.toJSONString(orderHistoryDTO));
        /****订单类型 2、支付、3、退款***/
        Integer orderType = orderHistoryDTO.getOrderType();
        ReqOrderOperate orderOperate = orderHistoryDTO.getReqOrderOperate();

        String orderNo = orderOperate.getOrderNo();
        TbBizPlaceOrder tbBizPlaceOrder = getPlaceOrder(orderNo);
        if(null == tbBizPlaceOrder){
            return APIResponse.returnFail("不存在订单信息！");
        }

        if (orderType.equals(2)){
            List<TbBizPlaceOrderItem> placeOrderItem = getPlaceOrderItem (orderNo);
            for (TbBizPlaceOrderItem orderItem : placeOrderItem) {
                TbBizPlaceOrderHistory orderHistory = new TbBizPlaceOrderHistory();
                orderHistory.setBusinessType((byte) 0);//交易类型：0：支付 1：退款
                orderHistory.setPlatform(tbBizPlaceOrder.getPlatform());
                orderHistory.setUseType(tbBizPlaceOrder.getUseType());
                orderHistory.setPlaceId(tbBizPlaceOrder.getPlaceId());
                orderHistory.setSourceType(tbBizPlaceOrder.getSourceType());
                orderHistory.setPlaceOrderId(orderOperate.getOrderNo());
                orderHistory.setUid(orderOperate.getUid());
                orderHistory.setAmount(orderItem.getSalePrice());
                orderHistory.setOrderItemUuid(orderItem.getItemUuid());
                byte useType = orderHistory.getUseType();
                if (useType == 2){
                    orderHistory.setTicketCount(orderItem.getTicketCount());
                }
                orderHistoryMapper.insertSelective(orderHistory);
            }
            logger.debug("========================插入订单历史流水记录:TbBizPlaceOrderHistory:{}", JSON.toJSONString(orderHistoryDTO));
        }else if (orderType.equals(3) || orderType.equals(4)){
            /**App端 门票不允许退款**/
            List<TbBizPlaceOrderItem> placeOrderItem = getPlaceOrderItem (orderNo);
            for (TbBizPlaceOrderItem orderItem : placeOrderItem) {
                TbBizPlaceOrderHistory orderHistory = new TbBizPlaceOrderHistory();
                orderHistory.setBusinessType((byte) 1);//交易类型：0：支付 1：退款
                orderHistory.setPlatform(tbBizPlaceOrder.getPlatform());
                orderHistory.setUseType(tbBizPlaceOrder.getUseType());
                orderHistory.setPlaceId(tbBizPlaceOrder.getPlaceId());
                orderHistory.setSourceType(tbBizPlaceOrder.getSourceType());
                orderHistory.setPlaceOrderId(orderOperate.getOrderNo());
                orderHistory.setUid(orderOperate.getUid());
                orderHistory.setAmount(orderItem.getSalePrice());
                orderHistory.setOrderItemUuid(orderItem.getItemUuid());
                orderHistoryMapper.insertSelective(orderHistory);
            }
            logger.debug("========================插入订场订单历史流水记录:TbBizPlaceOrderHistory:{}", JSON.toJSONString(orderHistoryDTO));
        }
        return null;
    }


    public static void main(String[] args) {
        /*BigDecimal temp = new BigDecimal(2.5);
        BigDecimal temp1 = new BigDecimal(0.15);
        BigDecimal temp2 = new BigDecimal(1.57);
        BigDecimal temp3 = new BigDecimal(0.4);
        System.out.println(temp.setScale(0, BigDecimal.ROUND_DOWN));
        System.out.println(temp1.setScale(0, BigDecimal.ROUND_DOWN));
        System.out.println(temp2.setScale(0, BigDecimal.ROUND_DOWN));
        System.out.println(temp3.setScale(0, BigDecimal.ROUND_DOWN));*/

        List<String> list = PlaceOrderUtil.getIntervalTimeList("08:30",
                "22:30", 0);
        System.out.println(JSON.toJSON(list));

    }
}
